export class ClickOutside {
  /**
   * @description:
   * @param {Array} ElementArray - [Element,...]
   * @param {Function} callback
   * @param {Boolean} handMode
   * - 是否启用手动调用offEvent模式,
   * - false 默认值 - 在执行callback时会自动调用offEvent
   * @example:
   */
  constructor(ElementArray = [], callback, handMode) {
    if (!callback) {
      throw new Error('callback is not defined');
    }
    if (typeof callback !== 'function') {
      throw new Error('callback is not a function');
    }
    this.ElementArray = ElementArray;
    this.callback = callback;
    this.handMode = handMode;
    this._isClickOutside = this._isClickOutside.bind(this);
    this.onEvent();
  }
  onEvent() {
    document.addEventListener('click', this._isClickOutside);
  }
  offEvent() {
    document.removeEventListener('click', this._isClickOutside);
  }
  _isClickOutside(e) {
    const path = e.composedPath();
    let isClickOutside = true;
    outer: for (let i = 0; i < path.length; i++) {
      const _dom = path[i];
      for (let j = 0; j < this.ElementArray.length; j++) {
        const _element = this.ElementArray[j];
        if (_dom === _element) {
          isClickOutside = false;
          break outer;
        }
      }
    }
    if (isClickOutside) {
      if (!this.handMode) {
        this.offEvent();
      }
      this.callback();
    }
  }
}
